package portal.monitor.action;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import beans.LogEnum;
import portal.action.rest.BaseAction;
import portal.common.MesageCode;
import portal.common.ResultData;
import portal.monitor.cmd.ScheCmd;
import portal.monitor.dao.BlackList;
import portal.monitor.service.BlackListService;
import portal.monitor.service.HostCtrlService;
import portal.monitor.service.ModeRecordService;
import portal.monitor.utils.MonBaseUtils;
import portal.monitor.utils.MonConfig;
import utils.Log4jInit;
import utils.UserLogUtil;

@RestController
@RequestMapping(value="/ws/remote/")
public class HostCtrlAction extends BaseAction {
	
	@Autowired
	public HostCtrlService hostCtrlService;
	@Autowired  
  private HttpServletRequest request;  
	@Autowired  
	public  ModeRecordService modeRecord;
	@Autowired  
	public BlackListService blackListService;

	/**
	 * 执行远程命令
	 * @param cmd
	 * @return
	 */
	/*@RequestMapping(value="/host/exec",method=RequestMethod.POST)
	public ResultData exec(String IPS,String cmd){
		
		String[] ipStr = IPS.split(MonConfig.conSplit);
		return hostCtrlService.exec(ipStr, cmd);
	}*/
	
	/**
	 * 执行脚本文件
	 * @param filePath
	 * @return
	 */
	/*@RequestMapping(value="/host/execScript",method=RequestMethod.GET)
	public ResultData execScript(String IPS,String filePath){
		String[] ipStr = IPS.split(MonConfig.conSplit);
		File file = new File(filePath);
		if(file.exists()&&file.isFile()){
			return hostCtrlService.execScript(ipStr, file);
		}
		ResultData result = new ResultData();
		result.setResultCode(MesageCode.ERROR);
		result.setDesc("操作失败");
		 
		return result;
	}
	*/
	/**
	 * 读取脚本列表
	 * @param filePath
	 * @return
	 */
	@RequestMapping(value="/host/readScript",method=RequestMethod.GET)
	public ResultData readScript(String scripType){

		//scripType: deploy / kill / start
			return hostCtrlService.readScript(scripType);
	}
	
	/**
	  * 推送文件  (批量文件到指定目录) execType=deploy时,安装该软件,且软件需为zip格式,包内第一层为安装程序.
	  * filePath为exe名
	 * @return
	 */
	@RequestMapping(value="/app/download",method=RequestMethod.POST)
	public ResultData postFile(String IPS,String filePath,String execType){
		
		ResultData result = new ResultData();
		String[] ipStr = IPS.split(MonConfig.conSplit);
//		String[] fileStr = filePath.split(MonConfig.conSplit);
		
			File file = new File(MonConfig.localBase+"deploy/"+filePath);
			try {
				MonBaseUtils.chmod(file.getAbsolutePath());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result.setResultCode(MesageCode.ERROR);
				result.setDesc("操作失败：文件权限错误");
				return result;
			}
			if(file.exists()&&file.isFile()){
				if((!StringUtils.isEmpty(execType)) &&	execType.equals("deploy")){
					String tmp = filePath.substring(filePath.lastIndexOf(".")+1);
					Log4jInit.logger.info("tmp:"+tmp);
					if(tmp.equals("zip"))  {
						return hostCtrlService.postFile(ipStr, filePath,true);
					}
				}else{
					return hostCtrlService.postFile(ipStr, filePath,false);
				}
			}
		
		
		UserLogUtil.dbLog(LogEnum.hostSend,
                LogEnum.execute,
                (String)request.getSession().getAttribute("userId"),
                LogEnum.hostSend.getValue()+"文件名："+filePath);
		result.setResultCode(MesageCode.ERROR);
		result.setDesc("操作失败：上传文件不存在");
		return result;
	}
	
	/**
	 * 获取节点信息
	 * 	type:mac / app / process  /usb
	 */
	@RequestMapping(value="/{type}/check",method=RequestMethod.GET)
	public ResultData check(String IP,@PathVariable("type") String type){
		ResultData result = hostCtrlService.execCmd(IP, type);
		//对app 已安装程序进行处理 与黑名单比对标记
		if(type.equals("app")){
			
			if(result.resultCode.equals(MesageCode.SUCCESS)){
				String record = (String)result.data;
				BlackList blacklist = new BlackList();
				blacklist.setValid(true);
				List<BlackList> list = blackListService.list(blacklist);
			  String[] lines = record.split("#");
			  StringBuffer sb = new StringBuffer();
			  for(int i=0;i<lines.length;i++){
				  for(BlackList bl:list){
					  if(lines[i].contains(bl.getAppName())){
						  lines[i] = "<p style=\"background-color:yellow\">"+lines[i]+"</p>";
					  }
				  }
				  sb.append(lines[i]);
				  sb.append("#");
				  
			  }
				result.data = sb.toString();
				result.desc = "SUCCESS";
				return result;
			}
		}
		
		return result;
	}
	
	
	
	/**
	 * 终止节点进程
	 * @param IP
	 * @param procs
	 * @return
	 */
	@RequestMapping(value="/proc/kill",method=RequestMethod.GET)
	public ResultData procKill(String IP,String procs){
	//	return hostCtrlService.execCmd(IP, type);
		System.out.println("***********"+procs);
		String[] procsArr = procs.split(",");
		return this.stopProc(IP, procsArr);
		//return hostCtrlService.execCmd(IP, procs);
	}
	
	//封装KP文件
private  ResultData stopProc(String IPS, String[] procs){
	
	StringBuffer sb = new StringBuffer();
	for(int k=0;k<procs.length;k++){
		sb.append(procs[k]);
		sb.append("\n");
	}
	
	File PLFile =MonBaseUtils.createFile(sb.toString(),MonConfig.localBase, "/PRC-KP.txt");
	
	ResultData rd = new ResultData();
//	for(int i=0;i<ips.length;i++){
		rd = ScheCmd.stopProc(IPS,PLFile.getAbsolutePath());		
//	}
	
		UserLogUtil.dbLog(LogEnum.hostDown,
                LogEnum.execute,
                (String)request.getSession().getAttribute("userId"),
                LogEnum.hostDown.getValue()+"节点："+IPS);
		return rd;
	}
	
@RequestMapping(value="/app/remove",method=RequestMethod.GET)
public ResultData removeFiles(String IPS,String procs){
	IPS = IPS.replaceAll(","," ");
	System.out.println("******"+procs+"  ips:"+IPS);
	return hostCtrlService.removeFiles(IPS, procs);
}


	/**
	 * 模式切换
	 * @param killType
	 * @param killIPS
	 * @param startType
	 * @param startIPS
	 * @return
	 */
	@RequestMapping(value="/mode/change",method=RequestMethod.GET)
	public ResultData modeChange(String startType,String startIPS){
		
		ResultData rd = new ResultData();
		if(StringUtils.isEmpty(startIPS)){
			rd.resultCode = MesageCode.ERROR;
			rd.data = "请勾选须操作的节点IP";
		}else{
			String[] IPS = startIPS.split(",");
			for(int i=0;i<IPS.length;i++){
				rd = this.stopMode(IPS[i]);
				if(rd.desc.equals("SUCCESS") && (!StringUtils.isEmpty(startType))){
					rd = this.startMode(IPS[i], startType);
				}
			}
			
		}
		UserLogUtil.dbLog(LogEnum.hostMode,
                LogEnum.execute,
                (String)request.getSession().getAttribute("userId"),
                LogEnum.hostMode.getValue()+"名称："+startType);
		return rd;
		
	}
	
private  ResultData stopMode(String IPS){
		
		Set<String> modeSet = modeRecord.getRecord(IPS);
		
		ResultData rd = new ResultData();
		if(modeSet.size()>0){
			Log4jInit.logger.info("mode set:"+modeSet.toString());
			for(String s:modeSet){   //modeSet : ModeName
				rd = ScheCmd.stopSche(IPS,s);
			}
			int count = modeRecord.delete(IPS);
			if(count<1){
				rd.resultCode = MesageCode.ERROR;
				rd.data = "数据删除错误";
			}
		}else{
			rd.resultCode = MesageCode.SUCCESS;
			rd.data = "终止成功，无运行中的模式";
		}
		UserLogUtil.dbLog(LogEnum.hostDown,
                LogEnum.execute,
                (String)request.getSession().getAttribute("userId"),
                LogEnum.hostDown.getValue()+"节点："+IPS);
		return rd;
	}

private ResultData startMode(String startIPS,String  startType){
	
//	ResultData rd = new ResultData();
	ResultData rd = ScheCmd.startSche(startIPS, startType);
	if(!rd.desc.equals("SUCCESS")){
		return rd;
	}
	int count = modeRecord.add(startIPS,startType);
	if(count>0){
		rd.resultCode = MesageCode.SUCCESS;
		rd.data = "模式启动成功";
	}else{
		rd.resultCode = MesageCode.ERROR;
		rd.data = "模型数据库添加失败";
	}
	
	return rd;
}
		
	
	/**
	 * 批量关机  (批量)
	 * @param IPs
	 * @return
	 */
	@RequestMapping(value="/host/shutdown",method=RequestMethod.GET)
	public ResultData shutdown(String IPS){
		String[] ipStr = IPS.split(MonConfig.conSplit);
		return hostCtrlService.shutdown(ipStr);
	}
	
	
	@RequestMapping(value="/app/upload",method=RequestMethod.POST)
	 public ResultData fileUpload(@RequestParam("file") CommonsMultipartFile file) {
		ResultData result = new ResultData();
        // 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
               // String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename();  
            	 String filePath = MonConfig.localBase + "deploy/";
            	 File f = new File(filePath);
            	 if((!f.exists())||f.isFile()){
            		 f.mkdirs();
            	 			}
            	 filePath += file.getOriginalFilename(); 
                // 转存文件  
                file.transferTo(new File(filePath));  
                MonBaseUtils.chmod(filePath);
            } catch (Exception e) {  
                e.printStackTrace(); 
                result.resultCode = MesageCode.ERROR;
                result.data = "上传失败";
                return result;
            }  
        }  
        // 重定向  
        result.resultCode = MesageCode.SUCCESS;
        result.data = "上传成功。";
        return result;
    }  
	
}
